package com.cimp.util.fuse;

import com.cimp.domain.common.Result;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * [简要描述]:HTTP工具类
 * [详细描述]:
 *
 * @author huojinhao
 * @date 2018/10/8
 */
public class HttpUtil {


    public static Result postMessage(String url, String content) {
        if (StringUtils.isBlank(url)) {
            Result result = Result.error("interface url is blank.");
//            DEBUGLOG.error(result.getResultMsg());
            return result;
        }
        // 参数初始化
        HttpURLConnection conn = null;
        BufferedWriter out = null;
        BufferedReader reader = null;

        try {
            // 设置地址
            URL u = new URL(url);

            conn = (HttpURLConnection) u.openConnection();

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", content.getBytes("UTF-8").length + "");
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");

            // 通过connection连接对象获取输出流对象
            out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            //将需要向客户端发送的信息写入到输出流  刷新输出流并且关闭流
            out.write(content);
            out.flush();
            int code = conn.getResponseCode();

            // 发送给第三方,获取返回结果
            if (code == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = null;
                StringBuffer buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }

                String response = buffer.toString();
                JSONObject object = JSONObject.fromObject(response);
                Result result = (Result) JSONObject.toBean(object, Result.class);
                return  result;
            } else {
                Result result = Result.error("interface return : " + code);
//                DEBUGLOG.error(result.getResultMsg());
                return result;
            }
        } catch (JSONException e) {
            Result result = Result.error("callback json parse error.");
//            DEBUGLOG.error(result.getResultMsg(), e);
            return result;
        } catch (Exception e) {
            Result result = Result.error("interface error.");
//            DEBUGLOG.error(result.getResultMsg(), e);
            return result;
        } finally {
            if (null != conn) {
                conn.disconnect();
            }
            try {
                if (null != out) {
                    out.close();
                }
                if (null != reader) {
                    reader.close();
                }
            } catch (Exception e) {
//                DEBUGLOG.error("connection close error.");
            }
        }
    }

    public static void sendResult(HttpServletResponse response, Result result) {
        JSONObject responseJson = new JSONObject();

        responseJson.put("resultCode", result.getResultCode());
        responseJson.put("resultMsg", result.getResultMsg());

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(responseJson.toString());
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
            }
            out = null;
        }
    }


    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }

    public static String doGet(String httpurl, Map<String, String> params) {
        String targetUrl = httpurl;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            targetUrl = targetUrl.replace("{" + key + "}", value);
        }
        return doGet(targetUrl);
    }

    public static InputStream doGetStream(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                return connection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }

        return is;
    }
}
